home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 15933 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  50 lines

  1. Newsgroups: comp.lang.c++
  2. Path: presby.edu!jtbell
  3. From: jtbell@presby.edu (Jon Bell)
  4. Subject: Re: Arrays or Pointers?
  5. Message-ID: <DpKEyB.I5K@presby.edu>
  6. Date: Mon, 8 Apr 1996 22:39:46 GMT
  7. References: <4kbsk3$f07@zeus.tcp.co.uk>
  8. Organization: Presbyterian College, Clinton, South Carolina USA
  9.  
  10.  David <daveg@tcp.co.uk> wrote:
  11. >I'm currently on a C++ course and we seem to be using pointers a fair
  12. >bit. On questioning this, was told that pointers where quicker than
  13. >using arrays. In which situations should I be using arrays over
  14. >pointers and vice versa?
  15.  
  16. Suppose you have the following array:
  17.  
  18.     double foo[100];
  19.  
  20. You can find the sum of the elements of the array either using
  21.  
  22.     sum = 0;
  23.     for (int k = 0; k < 100; k++)
  24.         sum += foo[k];
  25.  
  26. or using something like
  27.  
  28.     sum = 0;
  29.     double *p;
  30.     p = foo;
  31.     for (int k = 0; k < 100; k++)
  32.         sum += *p++;
  33.  
  34. If you have a really simple-minded compiler, for the first option it will
  35. generate code that re-calculates the address of foo[k] from scratch every
  36. time around the loop (which usually means a multiplication and an
  37. addition), instead of advancing a pointer through the array (a simple 
  38. addition) as in the second option. 
  39.  
  40. However, a reasonably smart compiler can generate the same code for both 
  41. situations, as someone else has already pointed out.  I myself prefer to 
  42. use array notation unless I absolutely have to use pointers, because it's 
  43. easier for me to make mistakes if I use pointers.  (So if I got the 
  44. details of the pointer example wrong, then it's also an example of why I 
  45. prefer arrays! :-))
  46.  
  47. -- 
  48. Jon Bell <jtbell@presby.edu>                        Presbyterian College
  49. Dept. of Physics and Computer Science        Clinton, South Carolina USA
  50.